package com.vincent.rocketmqdemo.config;

import java.util.Properties;

import javax.annotation.PostConstruct;

import com.vincent.rocketmqdemo.listener.RocketmqTest1Listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import org.springframework.util.StringUtils;

/**
 * rocketmq消费者启动初始化类
 * 同一个消费者可以消费不同的topic，同一个topic可以被不同的消费者消费（启用该方式相当于集群消费中的广播消费）
 *
 * @author hqc
 * @Date 2019年1月17日
 */
//@EnableConfigurationProperties(RocketMqProperties.class)
//@Component
public class RocketmqConsumerInit {

    private Logger logger = LoggerFactory.getLogger(RocketmqConsumerInit.class);

    @Autowired
    private RocketMqProperties rocketMqProperties;

    private static Consumer consumer;

    private String msgTopic = "chat_event_dev";


    @PostConstruct
    public void init() {
        System.out.println("初始化启动消费者者！");
        // consumer 实例配置初始化
        Properties properties = new Properties();
        //您在控制台创建的consumer ID
        properties.setProperty(PropertyKeyConst.ConsumerId, rocketMqProperties.getCustomerId());
        // AccessKey 阿里云身份验证，在阿里云服务器管理控制台创建
        properties.setProperty(PropertyKeyConst.AccessKey, rocketMqProperties.getAccessKey());
        // SecretKey 阿里云身份验证，在阿里云服务器管理控制台创建
        properties.setProperty(PropertyKeyConst.SecretKey, rocketMqProperties.getSecretKey());
        //设置发送超时时间，单位毫秒
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
        // 设置 TCP 接入域名(此处以公共云生产环境为例)，设置 TCP 接入域名，进入 MQ 控制台的消费者管理页面，在左侧操作栏单击获取接入点获取
        if (!StringUtils.isEmpty(rocketMqProperties.getOnsAddr())) {
            properties.setProperty(PropertyKeyConst.ONSAddr, rocketMqProperties.getOnsAddr());
        }
        if (!StringUtils.isEmpty(rocketMqProperties.getNameServerAddr())) {
            properties.setProperty(PropertyKeyConst.NAMESRV_ADDR, rocketMqProperties.getNameServerAddr());
        }
        consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe(msgTopic, "*", new RocketmqTest1Listener());//监听第一个topic，new对应的监听器
        consumer.start();
        logger.info("ConsumerConfig start success.");

    }

    /**
     * 初始化消费者
     *
     * @return
     */
    public Consumer getconsumer() {
        return consumer;
    }
}
